# -*- coding: utf-8 -*-

import os

class CopyObject:
    folder = ""
    srcObj = []
    tarObjs = []
    prefix = ['']
    
    def __init__(self, folder, srcObj, tarObjs, prefix=['', 'AO_', 'GL_']):
        self.folder = folder
        self.srcObj = srcObj
        self.tarObjs = tarObjs
        if len(prefix) == 0:
            self.prefix = ['']
        else:
            self.prefix = prefix

    def run(self):
        srcObj = [self.srcObj[0].upper(), self.srcObj[1]]
        #print self.folder
        #print self.tarObjs
        print self.prefix
        for root, dirs, files in os.walk(self.folder):
            #print root
            #print files
            for filename in files:
                #print filename
                fn = os.path.splitext(filename)
                cmpstr = fn[0] and fn[0].upper() or ""
                flcode = [pf for pf in self.prefix if cmpstr == pf + srcObj[0]]
                if len(flcode) > 0:
                    print fn[0].upper()
                    content = open(os.path.join(root, filename), "r").read()
                    for (code, caption) in self.tarObjs:
                        print os.path.join(root, flcode[0] + code + fn[1])
                        newCont = content.replace(srcObj[0], code)
                        if len(srcObj[1]) > 0 and len(caption) > 0:
                            print srcObj[1] + "\t" + caption
                            newCont = newCont.replace(srcObj[1], caption)
                        open(os.path.join(root, flcode[0] + code + fn[1]), "w").write(newCont)

from Tkinter import *

class WinApp:
    def __init__(self):
        self.root = Tk(className="オブジェクトコピーツール")
        font = ('ＭＳ Ｐゴシック', 11, NORMAL)
        frame0 = Frame(self.root)
        frame0.pack(side=TOP)
        label0 = Label(frame0, text="コピー元フォルダ：", font=font)
        label0.pack(side=LEFT)
        self.srcDir = Entry(frame0, font=font, width=40)
        self.srcDir.pack(side=LEFT)
        self.findDir = Button(frame0, text=u"参照", command=self.findFolder, font=font)
        self.findDir.pack(side=LEFT)
        frame1 = Frame(self.root)
        frame1.pack(side=TOP)
        label1 = Label(frame1, text=u"コピー元コード     ", font=font)
        label1.pack(side=LEFT)
        label11 = Label(frame1, text="コピー元キャプション", font=font)
        label11.pack(side=RIGHT)
        frame11 = Frame(self.root)
        frame11.pack(side=TOP)
        self.srcCtl = []
        self.srcCtl.append(Entry(frame11, font=font))
        self.srcCtl.append(Entry(frame11, font=font))
        self.srcCtl[0].pack(side=LEFT)
        self.srcCtl[1].pack(side=RIGHT)
        frame2 = Frame(self.root)
        frame2.pack(side=TOP)
        label2 = Label(frame2, text="コピー先コード     ", font=font)
        label2.pack(side=LEFT)
        label3 = Label(frame2, text="コピー先キャプション", font=font)
        label3.pack(side=RIGHT)
        frame3 = Frame(self.root)
        frame3.pack(side=TOP)
        self.tarCtl = []
        
        for i in range(0, 10):
            frameTemp = Frame(frame3)
            frameTemp.pack(side=BOTTOM)
            self.tarCtl.append((Entry(frameTemp, fg="blue", font=font), Entry(frameTemp, fg="blue", font=font)))
            self.tarCtl[i][0].pack(side=LEFT)
            self.tarCtl[i][1].pack(side=RIGHT)

        frame4 = Frame(self.root)
        frame4.pack(side=TOP)
        self.execute = Button(frame4, text="開始", command=self.start, font=font)
        self.execute.pack(side=RIGHT)
        self.saveSettings = Button(frame4, text="設定の保存", command=self.save, font=font)
        self.saveSettings.pack(side=LEFT)
        self.getSettings()
        self.root.mainloop()

    def findFolder(self):
        import tkFileDialog
        dlg = tkFileDialog.Directory()
        dlg.options['initialdir'] = self.srcDir.get()
        if dlg.show():
            self.srcDir.delete(0, END)
            self.srcDir.insert(INSERT, os.path.abspath(dlg.options['initialdir']))
            
    def getSettings(self):
        try:
            settings = open(os.path.join(os.path.curdir, "copyobject.cfg"), "r").read().split('\n')
        except:
            return
        settings = [setting.decode('cp932') for setting in settings]
        for i in range(0, 12):
            settings.append('')
        setVal = lambda ctrl, val: (ctrl.delete(0, END), ctrl.insert(INSERT, val))
        splitVal = lambda val: val.split(',', 2)
        if settings[0]:
            setVal(self.srcDir, settings[0])
        if settings[1]:
            vals = splitVal(settings[1])
            setVal(self.srcCtl[0], vals[0])
            setVal(self.srcCtl[1], vals[1])
        for i in range(2, 12):
            if settings[i]:
                vals = splitVal(settings[i])
                setVal(self.tarCtl[11-i][0], vals[0])
                setVal(self.tarCtl[11-i][1], vals[1])

    def save(self):
        fl = open(os.path.join(os.path.curdir, "copyobject.cfg"), "w")
        fl.write(self.srcDir.get() + '\n')
        fl.write(self.srcCtl[0].get() + ',' + self.srcCtl[1].get() + '\n')
        for i in range(9, -1, -1):
            fl.write(self.tarCtl[i][0].get() + ',' + self.tarCtl[i][1].get() + '\n')
        fl.close()        

    def start(self):
        srcObj = [self.srcCtl[0].get(), self.srcCtl[1].get().encode('cp932')]
        #print srcObj
        #print srcObj[1].encode('cp932')
        tarObj = [(ctl[0].get(), ctl[1].get().encode('cp932')) for ctl in self.tarCtl if len(ctl[0].get()) > 0]
        #print tarObj
        if len(srcObj[0]) > 0 and len(tarObj) > 0:
            copyObj = CopyObject(self.srcDir.get(), srcObj, tarObj)
            copyObj.run()

WinApp()
